<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Grid;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Villager;
use App\Models\Protocol;
use App\Models\Agent;
use App\Models\ProtocolSet;
use App\Models\GridArea;
use App\Models\GridHouse;
use App\Models\BuildForm;
use App\Models\GridImg;
use App\Models\GridPlan;
use App\Models\ApprovalSet;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

// 入户
class GridAreaController extends Controller
{
    // 拆迁意见回显
    public function opinionList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data=Grid::query()
        ->select('id','opinion','assess_company_id','mapping_company_id','house_use',
        'build_form','supply_form','dualuse_area','disagree_reason',
        'if_sign','for_user_id','if_mapping','if_build')
        ->where('id',$params['grid_id'])
        ->first();

        return showData($data);
    }

    // 拆迁意见录入
    public function addOpinion(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'id' => 'required',
            'opinion' => 'required',
        ], [
            'id.required' => '请输入网格id',
            'opinion.required' => '请输入拆迁意见',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $request->all();

        if($params['opinion']==1){
            if(!$params['mapping_company_id']&&$params['dualuse_area']){
                return showError('有兼用面积必须进行测绘');
            }
            $into_door_status = Grid::query()->where('id',$params['id'])->value('into_door_status');
            if($into_door_status == 0){
                $Info['into_door_status']=2;
            }
        }

        isset($params['opinion'])?$Info['opinion']=$params['opinion']:'';
        isset($params['assess_company_id'])?$Info['assess_company_id']=$params['assess_company_id']:$Info['assess_company_id']=0;
        isset($params['mapping_company_id'])?$Info['mapping_company_id']=$params['mapping_company_id']:$Info['mapping_company_id']=0;
        isset($params['house_use'])?$Info['house_use']=$params['house_use']:'';
        isset($params['build_form'])?$Info['build_form']=$params['build_form']:'';
        isset($params['supply_form'])?$Info['supply_form']=$params['supply_form']:'';
        isset($params['dualuse_area'])?$Info['dualuse_area']=$params['dualuse_area']:'';
        isset($params['disagree_reason'])?$Info['disagree_reason']=$params['disagree_reason']:'';
        isset($params['if_mapping'])?$Info['if_mapping']=$params['if_mapping']:$Info['if_mapping']=0;
        isset($params['if_build'])?$Info['if_build']=$params['if_build']:$Info['if_build']=0;
       

        $Info['for_user_id']=auth('api')->user()->id??0;
        try {
            $data = Grid::query()
            ->where('id',$params['id'])
            ->update($Info);
            return showSuccess('编辑成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
       
    }

    // 身份证录入回显
    public function idCardList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data=Grid::query()
        ->select('id','if_agent','receive_villager_id','if_sign','for_user_id','dualuse_area','business_imgs','business_num','business_award_time')
        ->where('id',$params['grid_id'])
        ->with('villager:id,name,identity_card,id_obverse_img,id_reverse_img,phone,grid_id,is_late')
        ->with('agent:name,identity_card,id_obverse_img,id_reverse_img,phone,grid_id')
        ->first();
        
        if($data){
            foreach($data['villager'] as &$v){
                $v['id_obverse_img']=$v['id_obverse_img']?$this->getImageUrl($v['id_obverse_img']):[];
                $v['id_reverse_img']=$v['id_reverse_img']?$this->getImageUrl($v['id_reverse_img']):[];
            }
    
            if($data['agent']){
                $data['agent']['id_obverse_img']=isset($data['agent']['id_obverse_img'])?$this->getImageUrl($data['agent']['id_obverse_img']):[];
                $data['agent']['id_reverse_img']=isset($data['agent']['id_reverse_img'])?$this->getImageUrl($data['agent']['id_reverse_img']):[];
            }

            $data['receive_villager_name']=Villager::query()->where('id',$data['receive_villager_id'])->value('name');
        
            $data['business_imgs']=$data['business_imgs']?$this->getImageUrl($data['business_imgs']):[];
        }

        return showData($data);
    }

    // 身份证录入
    public function addIdCard(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'villager_list' => 'required',
            'if_agent' => 'required',
            'receive_villager_name' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'villager_list.required' => '请输入村民信息',
            'if_agent.required' => '请输入是否需要代理',
            'receive_villager_name.required' => '请输入补偿款领取人',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $request->all();

        try {
            if(isset($params['villager_list'])){
                $villager_arr=json_decode($params['villager_list'],true);
                $del=Villager::query()
                    ->where('grid_id',$params['grid_id'])
                    ->whereNotIn('id',array_column($villager_arr,'id'))
                    ->delete();
                foreach($villager_arr as $v){
                    $villager_data['name']=$v['name'];
                    $villager_data['identity_card']=$v['identity_card'];
                    $villager_data['id_obverse_img']=!empty($v['id_obverse_img'])?$v['id_obverse_img']:0;
                    $villager_data['id_reverse_img']=!empty($v['id_reverse_img'])?$v['id_reverse_img']:0;
                    $villager_data['phone']=$v['phone'];
                    if(isset($v['id'])){
                        $update=Villager::query()->where('id',$v['id'])->update($villager_data);
                    }else{
                        $grid=Grid::query()->where('id',$params['grid_id'])->first();
                        
                        $villager_data['grid_id']=$params['grid_id'];
                        $villager_data['protocol_id']=$grid->id;
                        $villager_data['project_id']=$grid->project_id;
                        $add=Villager::query()->create($villager_data);
                    }
                }
            }

            if(isset($params['agent_list'])&&!empty($params['agent_list'])){
                $agent_arr=json_decode($params['agent_list'],true);
                $agent_data['name']=$agent_arr['name'];
                $agent_data['identity_card']=$agent_arr['identity_card'];
                $agent_data['id_obverse_img']=$agent_arr['id_obverse_img'];
                $agent_data['id_reverse_img']=$agent_arr['id_reverse_img'];
                $agent_data['phone']=$agent_arr['phone'];
                if(isset($agent_arr['id'])){
                    $update=Agent::query()->where('id',$agent_arr['id'])->update($agent_data);
                }else{
                    $del=Agent::query()->where('grid_id',$params['grid_id'])->delete();
                    $agent_data['grid_id']=$params['grid_id'];
                    $add=Agent::query()->create($agent_data);
                }
            }

            $this->setRuhuStatus($params['grid_id'],'idcard_status');

            $grid_data['if_agent']=$params['if_agent'];
            $receive_villager_id=Villager::query()->where('grid_id',$params['grid_id'])->where('name',$params['receive_villager_name'])->value('id');
            $grid_data['receive_villager_id']=$receive_villager_id;
            isset($params['business_imgs'])?$grid_data['business_imgs']=$params['business_imgs']:'';
            isset($params['business_num'])?$grid_data['business_num']=$params['business_num']:'';
            isset($params['business_award_time'])?$grid_data['business_award_time']=$params['business_award_time']:'';
            $update=Grid::query()->where('id',$params['grid_id'])->update($grid_data);

            return showSuccess('提交成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 面积确认表回显
    public function areaList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'type' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data=Grid::query()
        ->select('id','name','house_use','supply_form','build_form','street_id','village_id','project_id','segment_id','address','business_num','business_award_time','business_imgs','dualuse_area','assess_company_id','mapping_company_id','if_sign','for_user_id','if_mapping','if_build')
        ->where('id',$params['grid_id'])
        ->with('villager:id,name,identity_card,phone,grid_id')
        ->with(['grid_area'=> function ($query) use ($params) {
            $query->where('type', $params['type']);
        }])
        ->with(['grid_house' => function ($query) {
            $query->where('type', 2)->with('house_type:id,name,area');
        }])
        ->with('agent:name,identity_card,phone,grid_id')
        ->first()
        ->toArray();

        foreach($data['grid_house'] as &$v){
            $v['villager']=Villager::query()->select('id','name')->whereIn('id',explode(',',$v['villager_ids']))->get()->toArray();
        }

        $data['business_imgs']=$data['business_imgs']?$this->getImageUrl($data['business_imgs']):[];
        $data['build_form_name']=BuildForm::query()->where('id',$data['build_form'])->value('name');

        $data['protocol_set']=ProtocolSet::query()
        ->select('id','reward_area','improve_area','public_area_scale','upper_lean','lower_lean')
        ->where('supply_form',$data['supply_form'])
        ->where('build_form',$data['build_form'])
        ->where('street_id',$data['street_id'])
        ->where('village_id',$data['village_id'])
        ->where('project_id',$data['project_id'])
        ->where('segment_id',$data['segment_id'])
        ->first();

        if(empty($data['protocol_set'])){
            return showError('未查询到配置信息，请联系管理员到后台配置');
        }

        if($data['grid_area']){
            $data['grid_area']['mapping_content']=json_decode($data['grid_area']['mapping_content'],true);
            if($data['grid_area']['mapping_content']){
                foreach($data['grid_area']['mapping_content'] as &$v){
                   $v['img']=$v['img']?$this->getImageUrl($v['img']):[];
                } 
            }
            $data['grid_area']['area_imgs']=$data['grid_area']['area_imgs']?$this->getImageUrl($data['grid_area']['area_imgs'],1):[];
        }
       
        return showData($data);
    }
    
    // 面积确认表上传
    public function addArea(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'type' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $request->all();

        $GridAreaInfo=$this->getDate($params);
        if (isset($GridAreaInfo['code']) && $GridAreaInfo['code'] == 0) {
            return $GridAreaInfo;
        }
        if(isset($params['dualuse_area'])){
            if($GridAreaInfo['actual_area']<$params['dualuse_area']){
                return showError('兼用面积不可大于实际总面积');
            }
        }
        unset($GridAreaInfo['actual_area']);

        try{
            $GridAreaInfo['grid_id']=$params['grid_id'];
            $GridAreaInfo['type']=$params['type'];
            $GridAreaInfo['do_user_id']=auth('api')->user()->id??0;
            isset($params['dualuse_area'])?$GridAreaInfo['dualuse_area']=$params['dualuse_area']:'';
            isset($params['mapping_content'])?$GridAreaInfo['mapping_content']=$params['mapping_content']:'';
            isset($params['area_imgs'])?$GridAreaInfo['area_imgs']=$params['area_imgs']:'';

            isset($params['address'])?$GridInfo['address']=$params['address']:'';
            isset($params['business_imgs'])?$GridInfo['business_imgs']=$params['business_imgs']:'';
            isset($params['business_num'])?$GridInfo['business_num']=$params['business_num']:'';
            isset($params['business_award_time'])?$GridInfo['business_award_time']=$params['business_award_time']:'';

            if(isset($GridInfo)){
                $Grid=Grid::query()->where('id',$params['grid_id'])->update($GridInfo);
            }

            $GridArea = GridArea::query()->updateOrCreate(
                [
                    'grid_id' => $params['grid_id'],
                    'type' => $params['type'],
                ],$GridAreaInfo);

            if(isset($params['house_type'])&&!empty($params['house_type'])&&$params['type']==1){
                $house_type_arr=json_decode($params['house_type'],true);
                $del=GridHouse::query()
                     ->where('grid_id',$params['grid_id'])
                     ->where('type',2)
                     ->whereNotIn('id',array_column($house_type_arr,'id'))
                     ->delete();
                foreach($house_type_arr as $v){
                    $house_data['house_type_id']=$v['house_type_id'];
                    $house_data['is_decorate']=$v['is_decorate'];
                    $house_data['villager_ids']=$v['villager_ids'];
                    $house_data['do_user_id']=auth('api')->user()->id??0;
                    if(isset($v['id'])){
                        $update=GridHouse::query()->where('id',$v['id'])->update($house_data);
                    }else{
                        $house_data['grid_id']=$params['grid_id'];
                        $house_data['type']=2;
                        $add=GridHouse::query()->create($house_data);
                    }
                }
            }

            if($params['type']==1){
                $this->setRuhuStatus($params['grid_id'],'area_status');
            }elseif($params['type']==2){
                $find_grid=Grid::query()->select('dualuse_area','if_mapping','if_build')->where('id',$params['grid_id'])->first();
               
                if(!isset($params['table_type'])){//正常环节提交(非拒绝后)
                    if($find_grid['dualuse_area']==1){
                        // 触发审批-兼用面积
                        if(!$this->findApproval($params['grid_id'], 16)){
                            $this->setApproval($params['grid_id'],16);
                        }
                    }

                    if($find_grid['if_build']==1){
                        // 触发审批-有建房手续
                        if(!$this->findApproval($params['grid_id'], 17)){
                            $this->setApproval($params['grid_id'],17);
                            return showSuccess('提交成功！');
                        }
                    }

                    if($find_grid['if_build']==2){
                        // 触发审批-无建房手续
                        if(!$this->findApproval($params['grid_id'], 18)){
                            $this->setApproval($params['grid_id'],18);
                            return showSuccess('提交成功！');
                        }
                    }

                    if($find_grid['if_mapping']==1){
                        // 触发审批-有异议表
                        if(!$this->findApproval($params['grid_id'], 15)){
                            $this->setApproval($params['grid_id'],15);
                        }
                    }

                    if($find_grid['if_mapping']==2&&$find_grid['dualuse_area']==1){
                        // 触发审批-无异议表
                        if(!$this->findApproval($params['grid_id'], 14)){
                            $this->setApproval($params['grid_id'],14);
                        }
                    }

                    // 处理完成状态
                    $grid=Grid::query()->select('project_id','street_id','village_id')->where('id',$params['grid_id'])->first();
                    $approval_set=ApprovalSet::query()
                    ->where('project_id',$grid['project_id']??2)
                    ->where('street_id',$grid['street_id']??3)
                    ->where('village_id',$grid['village_id']??1)
                    ->where('template_id',26)
                    ->where('status',1)
                    ->value('id');
                    if($approval_set){//有审批
                        Grid::query()->where('id',$params['grid_id'])->update(['mapping_status'=>2]);

                        // 触发审批-完成测绘
                        if(!$this->findApproval($params['grid_id'], 26)){
                            $this->setApproval($params['grid_id'],26);
                        }
                    }else{
                        Grid::query()->where('id',$params['grid_id'])->update(['mapping_status'=>1]);
                    }    
                }


            }

            return showSuccess('提交成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 获取对应面积参数
    public function getDate($params){
       $grid= Grid::query()->select('id','build_form','supply_form','pid')->where('id',$params['grid_id'])->first();

       $pid= Grid::query()->where('pid',$params['grid_id'])->value('pid');
       if($grid['pid']||$pid){//有拆分(子/父)
          $pid=$pid?$pid:$grid['pid'];
          $GridPlan = GridPlan::query()->where('grid_id',$pid)->where('type',$params['type'])->first();
          if($GridPlan){
            $pluck_id = Grid::query()->where('pid',$pid)->pluck('id')->toArray();
            array_push($pluck_id,$pid);
            $use_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('use_area');
            if($use_area+$params['use_area']>$GridPlan['use_area']){
                return showError("当前使用面积最大输入值为".($GridPlan['use_area']-$use_area));  
            }
            $two_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('two_area');
            if($two_area+$params['two_area']>$GridPlan['two_area']){
                return showError('当前二层面积最大输入值为'.($GridPlan['two_area']-$two_area));  
            }
            $build_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('build_area');
            if($build_area+$params['build_area']>$GridPlan['build_area']){
                return showError('当前建筑面积最大输入值为'.($GridPlan['build_area']-$build_area));  
            }
            $yard_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('yard_area');
            if($yard_area+$params['yard_area']>$GridPlan['yard_area']){
                return showError('当前院落面积最大输入值为'.($GridPlan['yard_area']-$yard_area));  
            }
            $lack_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('lack_area');
            if($lack_area+$params['lack_area']>$GridPlan['lack_area']){
                return showError('当前不足45㎡面积最大输入值为'.($GridPlan['lack_area']-$lack_area));  
            }
            $basement_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('basement_area');
            if($basement_area+$params['basement_area']>$GridPlan['basement_area']){
                return showError('当前地下室面积最大输入值为'.($GridPlan['basement_area']-$basement_area));  
            }
            $dualuse_area = GridArea::query()->whereIn('grid_id',$pluck_id)->where('grid_id','<>',$params['grid_id'])->where('type',$params['type'])->sum('dualuse_area');
            if($dualuse_area+$params['dualuse_area']>$GridPlan['dualuse_area']){
                return showError('当前兼用面积最大输入值为'.($GridPlan['dualuse_area']-$dualuse_area));  
            }
          } 
       }

       $type=$grid['supply_form'].','.$grid['build_form'];
       switch ($type) {
                case '2,1'://房屋-带院住宅
                    $data['use_area']=$params['use_area'];
                    $data['two_area']=$params['two_area'];
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['supply_area']=$params['use_area']+$params['two_area']+$params['reward_area'];
                    $data['actual_area']=$params['use_area']+$params['two_area'];//实际面积
                break;   
                case '2,2'://房屋-多层楼房
                    $data['build_area']=$params['build_area'];
                    $data['basement_area']=$params['basement_area'];
                    $data['improve_area']=$params['improve_area'];//改善面积
                    $data['public_area']=$params['public_area'];//公摊面积
                    $data['supply_area']=$params['build_area']+$params['improve_area']+$params['public_area'];
                    $data['actual_area']=$params['build_area']+$params['basement_area'];//实际面积
                break;   
                case '2,3'://房屋-不足35㎡
                    $data['build_area']=$params['build_area'];
                    $data['basement_area']=$params['basement_area'];
                    $data['lack_area']=$params['lack_area'];//不足45㎡面积
                    $data['public_area']=$params['public_area'];//公摊面积
                    $data['supply_area']=$params['lack_area']+$params['public_area'];
                    $data['actual_area']=$params['build_area']+$params['basement_area'];//实际面积
                break; 
                case '2,4'://房屋-平房
                    $data['use_area']=$params['use_area'];
                    $data['two_area']=$params['two_area'];
                    $data['yard_area']=$params['yard_area'];//院落面积
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['supply_area']=$params['use_area']+$params['two_area']+$params['reward_area'];
                    $data['actual_area']=$params['use_area']+$params['two_area']+$params['yard_area'];//实际面积
                break;  
                case '2,5'://房屋-二层及以上带院楼房
                    $data['use_area']=$params['use_area'];
                    $data['two_area']=$params['two_area'];
                    $data['yard_area']=$params['yard_area'];//院落面积
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['supply_area']=$params['use_area']+$params['two_area']+$params['reward_area'];
                    $data['actual_area']=$params['use_area']+$params['two_area']+$params['yard_area'];//实际面积
                break;     
                case '1,1'://货币-带院住宅
                    $data['build_area']=$params['build_area'];
                    $data['yard_area']=$params['yard_area'];//院落面积
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['improve_area']=$params['improve_area'];//改善面积
                    $data['supply_area']=$params['build_area']+$params['reward_area']+$params['improve_area'];
                    $data['actual_area']=$params['build_area']+$params['yard_area'];//实际面积
                break;   
                case '1,2'://货币-多层楼房
                    $data['build_area']=$params['build_area'];
                    $data['basement_area']=$params['basement_area'];
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['improve_area']=$params['improve_area'];//改善面积
                    $data['public_area']=$params['public_area'];//公摊面积
                    $data['supply_area']=$params['build_area']+$params['reward_area']+$params['improve_area'];
                    $data['actual_area']=$params['build_area']+$params['basement_area'];//实际面积
                break;   
                case '1,3'://货币-不足35㎡
                    $data['build_area']=$params['build_area'];
                    $data['basement_area']=$params['basement_area'];
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['public_area']=$params['public_area'];//公摊面积
                    $data['lack_area']=$params['lack_area'];//不足45㎡面积
                    $data['supply_area']=$params['reward_area']+$params['public_area']+$params['lack_area'];
                    $data['actual_area']=$params['build_area']+$params['basement_area'];//实际面积
                break; 
                case '1,4'://货币-平房
                    $data['build_area']=$params['build_area'];
                    $data['yard_area']=$params['yard_area'];//院落面积
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['improve_area']=$params['improve_area'];//改善面积
                    // $data['supply_area']=$params['build_area']+$params['reward_area']+$params['improve_area'];
                    $data['supply_area']=$params['build_area']+$params['improve_area'];
                    $data['actual_area']=$params['build_area']+$params['yard_area'];//实际面积
                break;  
                case '1,5'://货币-二层及以上带院楼房
                    $data['build_area']=$params['build_area'];
                    $data['yard_area']=$params['yard_area'];//院落面积
                    $data['reward_area']=$params['reward_area'];//奖励面积
                    $data['improve_area']=$params['improve_area'];//改善面积
                    // $data['supply_area']=$params['build_area']+$params['reward_area']+$params['improve_area'];
                    $data['supply_area']=$params['build_area']+$params['improve_area'];
                    $data['actual_area']=$params['build_area']+$params['yard_area'];//实际面积
                break; 
                case '1,6'://货币-工业-集体
                    $data['collective_area']=$params['collective_area'];
                    $data['supply_area']=$params['collective_area'];
                break;  
                case '1,7'://货币-工业-国有
                    $data['country_area']=$params['country_area'];
                    $data['supply_area']=$params['country_area'];
                break;  
                case '1,8'://货币-工业-国有及集体
                    $data['collective_area']=$params['collective_area'];
                    $data['country_area']=$params['country_area'];
                    $data['supply_area']=$params['collective_area']+$params['country_area'];
                break;      
                default:
                    return showError('类型错误');  
        }
       
        return $data;
    }
}

